package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"good_srv/cache"
	"good_srv/good"
	"good_srv/internal/svc"
	"good_srv/models"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdatePasswordLogic) UpdatePassword(in *good.UpdatePasswordRequest) (*good.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	users := models.User{
		Password: in.Password,
	}
	models.DB.Where("phone=?", in.Phone).Find(&users)
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
	if result != in.SendCode {
		return nil, fmt.Errorf("验证码失效")
	}
	if in.Password != in.NewPassword {
		logx.Error("新密码和确认密码输入错误,修改失败")
		return nil, fmt.Errorf("新密码和确认密码输入错误,修改失败")
	}
	if in.Password == users.Password {
		logx.Error("新旧密码相同,修改失败")
		return nil, fmt.Errorf("新旧密码相同,修改失败")
	}
	users.Password = in.Password
	models.DB.Updates(&users)
	return &good.UpdatePasswordResponse{
		Id: int64(users.ID),
	}, nil
}
